/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable import/no-extraneous-dependencies */
/**
 * 保管费设置
 */
import React, { Component } from 'react';
import { Form, Input, Button, Table, Alert, message } from 'antd';
import { connect } from 'dva';
import { debounce } from 'lodash';
import styles from './style.less';
import ChangeFeeModal from './components/modal';

const FormItem = Form.Item;

@connect(({ loading, dispat }) => ({
  dispat,
  getStorageFeeSettingList: loading.effects['dispat/getStorageFeeSettingList'],
  changeFee: loading.effects['dispat/changeFee'],
}))
@Form.create({ name: 'storageFeeSearch' })
class StorageFeeSetting extends Component {
  state = {
    visible: false,
    searchValue: { keywords: '' },
    id: null,
    page: 1,
    record: {},
  };

  handleSearch = debounce(
    e => {
      e.preventDefault();
      const { dispatch } = this.props;
      this.getFormValue(values => {
        dispatch({
          type: 'dispat/getStorageFeeSettingList',
          payload: {
            ...values,
            page: 1,
          },
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  handleTableChange = debounce(
    pagination => {
      const { searchValue } = this.state;
      const params = {
        page: pagination.current,
        ...searchValue,
      };
      this.setState({ page: pagination.current });
      this.getList(params);
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  componentDidMount() {
    this.getList({ keywords: '', page: 1 });
  }

  getList = ({ keywords, page }) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dispat/getStorageFeeSettingList',
      payload: {
        keywords,
        page,
      },
    });
  };

  getFormValue = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };

      this.setState({
        searchValue: values,
      });

      then(values);
    });
  };

  showModal = async values => {
    const { brand_fee = [], cm_id } = values;
    const { data } = await this.getBrands(cm_id);
    const getOpenBrands = Array.isArray(data) ? data : [];
    if (getOpenBrands.length === 0) {
      message.error('该驿站没有添加任何品牌');
      return;
    }
    const brandFee = Array.isArray(brand_fee) ? brand_fee : [];
    const formatFeeSetting = getOpenBrands.map(item => ({
      brand: item.brand_en,
      fee: brandFee.find(itemm => itemm.brand === item.brand_en)?.fee || '0', // 不给默认值没法编辑？,
      brand_cn: item.brand,
    }));
    console.info('getOpenBrands===>', getOpenBrands);
    this.setState({
      visible: true,
      id: values.cm_id,
      record: {
        ...values,
        feeSettings: formatFeeSetting,
      },
    });
  };

  getBrands = cm_id => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'dispat/getOpenBrands',
      payload: { cm_id },
    });
  };

  handleCancel = () => {
    const {
      form: { resetFields },
    } = this.formRef.props;
    resetFields();
    this.setState({
      visible: false,
    });
  };

  handleOk = () => {
    const { dispatch } = this.props;
    const { form } = this.formRef.props;
    const { id, searchValue, page, record: { price = '' } = {} } = this.state;
    form.validateFields((err, values) => {
      if (err) return;
      const brand_fee = values?.fee?.filter(item => !!parseFloat(item.fee || 0));
      dispatch({
        type: 'dispat/changeFee',
        payload: {
          id,
          price,
          brand_fee,
        },
      }).then(() => {
        this.getList({ keywords: searchValue.keywords, page });
      });

      form.resetFields();
      this.setState({
        visible: false,
      });
    });
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  render() {
    const { visible, record } = this.state;
    const {
      dispat: { storageFeeSetting },
      form: { getFieldDecorator },
      getStorageFeeSettingList,
    } = this.props;
    const columns = [
      {
        key: 'phone',
        title: '下属驿站注册手机号',
        dataIndex: 'phone',
      },
      {
        key: 'cm_id',
        title: '驿站名称',
        dataIndex: 'company_name',
      },
      {
        key: 'price',
        title: '每单入库保管费',
        dataIndex: 'price',
        render: (text, recordItem) => {
          const { brand_fee = [] } = recordItem || {};
          if (brand_fee.length === 0) {
            return (
              <div>
                <a onClick={() => this.showModal(recordItem)}>修改</a>
              </div>
            );
          }
          if (brand_fee.length) {
            return (
              <div>
                <a onClick={() => this.showModal(recordItem)}>
                  {brand_fee.reduce((pre, next) => `${pre}${next.brand_short} ${next.fee} `, '')}
                </a>
              </div>
            );
          }
          return <div />;
        },
      },
      {
        title: '修改时间',
        dataIndex: 'update_at',
        key: 'update_at',
      },
    ];

    const pagination = storageFeeSetting.pagination
      ? {
          showQuickJumper: false,
          current: storageFeeSetting.pagination.current * 1, // number类型
          total: storageFeeSetting.pagination.total * 1,
        }
      : false;

    return (
      <div style={{ paddingTop: 10 }}>
        <Alert
          message={
            <span>
              1、保管费是加盟商付给下属站点的费用，一般视为给驿站的派费。
              <br />
              2、例如：当您设置保管费价格为0.5元/件，则下属驿站每入库一件，在驿站APP账户记一笔账：收入0.5元（未到账）。
              <br />
              3、当您在【保管费发放】中进行手动发放，则从您的账户内扣除0.5元，发放到下属驿站的驿站App账户：收入0.5元（已到账）。
            </span>
          }
          type="warning"
          style={{ marginBottom: 20 }}
        />
        <Form
          onSubmit={this.handleSearch}
          className={styles['search-form']}
          layout="inline"
          style={{ marginBottom: 24 }}
        >
          <FormItem>
            {getFieldDecorator('keywords', {
              initialValue: '',
            })(
              <Input
                style={{ width: 350 }}
                placeholder="请输入快宝驿站的注册手机号、或驿站名称查询"
              />,
            )}
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              htmlType="submit"
              key="search"
              icon="search"
              loading={getStorageFeeSettingList}
            >
              查询
            </Button>
          </FormItem>
        </Form>
        <Table
          rowKey="cm_id"
          loading={getStorageFeeSettingList}
          dataSource={storageFeeSetting.list}
          columns={columns}
          pagination={pagination}
          onChange={this.handleTableChange}
        />
        <ChangeFeeModal
          wrappedComponentRef={this.saveFormRef}
          visible={visible}
          onCancel={this.handleCancel}
          onCreate={this.handleOk}
          record={record}
          title="设置入库保管费"
          type="setting"
        />
      </div>
    );
  }
}

export default StorageFeeSetting;
